package com.tensquare.spit.service;

import com.tensquare.entity.PageResult;
import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zzb
 * @create 2021/2/21
 */
@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    //查询全部吐槽
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    //根据id查询吐槽
    public Spit findById(String spitId) {
         return spitDao.findById(spitId).get();
    }

    //添加吐槽
    public void add(Spit spit) {
        spitDao.save(spit);
    }

    //修改吐槽
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    //根据id删除吐槽
    public void delete(String spitId) {
        spitDao.deleteById(spitId);
    }

    //根据父id查询吐槽列表
    public PageResult<Spit> comment(String parentid, Integer page, Integer size) {
        //根据父id进行分页查询
        Page<Spit> spitList = spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
        //返回自定义分页对象
        return new PageResult<>(spitList.getTotalElements(),spitList.getContent());
    }

    //点赞处理
    public Boolean thumbup(String spitId) {
        //从redis中拿到第一次点赞存放的数据
        Object obj = redisTemplate.opsForValue().get("thumbup_" + spitId);
        if (obj == null){//此时代表没点赞过
            //(传统方法)
            //根据id查询点赞对象
            Spit spit = spitDao.findById(spitId).get();
            //修改点赞数
            spit.setThumbup(spit.getThumbup()+1);
            //保存
            spitDao.save(spit);
            //将一个数据放到redis中代表点赞过
            redisTemplate.opsForValue().set("thumbup_"+spitId,"test");
            return true;
        }
        return false;

    }

    //点赞处理
//    public Boolean thumbup2(String spitId){
//        //判断是否有值
//        Object obj = redisTemplate.opsForValue().get("thumbup_" + spitId);
//        if(obj == null){
//            //定义查询条件
//            Query query = new Query();
//            query.addCriteria(Criteria.where("_id").is(spitId));
//            Update update = new Update();
//            update.inc("thumbup",1);
//            mongoTemplate.updateFirst(query,update,"spit");
//
//        }
//    }
}
